package com.feilo.controller;

import java.text.ParseException;
import java.util.List;

import org.json.JSONArray;

import com.feilo.service.AccountService;
import com.feilo.service.ImeiDataService;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class GpsDataController extends Controller {
	
	/**
	 * 初始化界面
	 */
	public void init(){
		render("/init.html");
	}
	
	/**
	 * 登录界面
	 */
	public void login(){
		render("/login.html");
	}
	
	/**
	 * 登录操作
	 */
	public void doLogin(){
		String account = getPara("account");
		String pwd = getPara("pwd");
		int id = AccountService.login(account, pwd);
		if(id>0){
			getSession().setAttribute("id", id);
			getSession().setAttribute("account", account);
			render("/imeilist.html");
		}else{
			render("/login.html");
		}
	}
	
	/**
	 * 设备号列表页面
	 */
	public void imeilist(){
		render("/imeilist.html");
	}
	
	
	/**
	 * 添加设备号（可批量添加）
	 */
	public void addImei(){
		int accountid = Integer.parseInt(getSession().getAttribute("id").toString());
		List<Record> imeisFromImeiData = ImeiDataService.getImeisFromImeiData(accountid);
		String data = getPara("data");
		JSONArray ar = new JSONArray(data);
		String imeisFromWeb = ar.getJSONObject(0).get("remarks").toString();
		String[] imeisFromWebArray = imeisFromWeb.split(",");
		for(String imeiFromWeb : imeisFromWebArray){
			boolean flag = true ;
			for(Record record : imeisFromImeiData){
				String imei = record.get("imei").toString();
				if(imeiFromWeb.equals(imei)){
					flag = false ;
					break ;
				}
			}
			if(flag){
				int imei = ImeiDataService.insertImeiToImeiData(imeiFromWeb);
				AccountService.insertImeiToAccountImei(accountid,imei);
				flag = false ;
			}
		}
	}
	
	/**
	 * 删除设备号（可批量删除）
	 */
	public void delImei(){
		String data = getPara("data");
		String ids[]  = data.split(",");
		for(int i = 0 ;i<ids.length;i++){
			String sql = "delete from imeidata where id=?" ;
			Db.update(sql, new Object[]{ids[i]});
		}
	}

	public void doInit() throws ParseException {
		render("/init.html");
	}
}
